package com.example.mediademo.muxer;

import android.content.Context;
import android.media.MediaCodec;
import android.media.MediaFormat;
import android.media.MediaMuxer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.example.mediademo.HandlerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MyMuxer {

    public static final int REPACK_SUCCESS = 10;
    public static final int REPACK_FAILED = 11;

    private String TAG = "MyMuxer";

    private String mPath;

    private MediaMuxer mediaMuxer;

    private int mVideoTrackIndex;

    private int mAudioTrackIndex;

    private boolean mIsAudioTrackAdd;

    private boolean mIsVideoTrackAdd;

    private boolean mIsStart;

    private String fileName;
    private String filePath;


    /**
     * 指定了封装的格式和路径
     */
    public MyMuxer(Context context) {
        fileName = "MyVidedo_" + new SimpleDateFormat("yyyyMM_dd-HHmmss").format(new Date()) + ".mp4";
        filePath = context.getExternalFilesDir(null).getAbsolutePath() + File.separator;
        Log.d(TAG,"打包路径:" + filePath);
        mPath = filePath + fileName;
        try {
            mediaMuxer = new MediaMuxer(mPath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);
        } catch (IOException e) {
            Log.e(TAG,"创建MediaMuxer出错:" + e.toString());
        }
    }

    // 添加音视频轨道
    // 设置音视频流格式，获取轨道索引，并启动Muxer

    public void addVideoTrack(MediaFormat mediaFormat) {
        try {
            if (mediaMuxer != null) {
                mVideoTrackIndex = mediaMuxer.addTrack(mediaFormat);
                mIsVideoTrackAdd = true;
                startMuxer();
            }
        } catch (Exception e) {
            Log.e(TAG,"addVideoTrack出错:" + e.toString());
        }
    }

    public void addAudioTrack(MediaFormat mediaFormat) {
        try {
            if (mediaMuxer != null) {
                mAudioTrackIndex = mediaMuxer.addTrack(mediaFormat);
                mIsAudioTrackAdd = true;
                startMuxer();
            }
        } catch (Exception e) {
            Log.e(TAG,"addVideoTrack出错:" + e.toString());
        }
    }

    // 写入音视频数据

    public void writeVideoData(ByteBuffer byteBuffer, MediaCodec.BufferInfo bufferInfo) {
        if (mIsStart) {
            if (mediaMuxer != null) {
                mediaMuxer.writeSampleData(mVideoTrackIndex,byteBuffer,bufferInfo);
            }
        }
    }

    public void writeAudioData(ByteBuffer byteBuffer,MediaCodec.BufferInfo bufferInfo) {
        if (mIsStart) {
            if (mediaMuxer != null) {
                mediaMuxer.writeSampleData(mAudioTrackIndex,byteBuffer,bufferInfo);
            }
        }
    }

    // 释放Muxer，必须释放才能成功生成文件

    public void release() {
        mIsAudioTrackAdd = false;
        mIsVideoTrackAdd = false;
        try {
            if (mediaMuxer != null) {
                mediaMuxer.stop();
                mediaMuxer.release();
                mediaMuxer = null;
                Log.d(TAG,"释放Muxer");
                sendMsgToActivity(filePath+ fileName,REPACK_SUCCESS);
            }
        } catch (Exception e) {
            Log.e(TAG,"释放Muxer出错:" + e.toString());
            sendMsgToActivity("释放Muxer出错:" + e.toString(),REPACK_FAILED);
        }
    }

    public void sendMsgToActivity(String message,int messageType) {
        Handler handler = HandlerFactory.getMainHandler();
        Message message1 = Message.obtain();
        message1.what = messageType;
        message1.obj = message;
        handler.sendMessage(message1);
    }

    public void setNoAudio() {
        if (mIsAudioTrackAdd) {
            return;
        }
        mIsAudioTrackAdd = true;
        startMuxer();
    }

    public void setNoVideo() {
        if (mIsVideoTrackAdd) {
            return;
        }
        mIsVideoTrackAdd = true;
        startMuxer();
    }

    /**
     * 启动MediaMuxer
     */
    private void startMuxer() {
        if (mIsVideoTrackAdd && mIsAudioTrackAdd) {
            mediaMuxer.start();
            mIsStart = true;
            Log.d(TAG,"启动MyMuxer，等待数据输入");
        }
    }

}
